<?php
namespace Util;
use Think\Controller;
//聚合数据短信API服务
class Sms extends Controller {
	private $sendUrl =  'http://v.juhe.cn/sms/send';
    private $key = '0e4f15984f8aa45820d286233ffa9870';
     /**
     * 发送短信
     * @param  string $mobile [手机号]
     * @return 
     */
    public function sendSMS($mobile,$tpl_id,$tpl_value){
        $msg = array('returnCode'=>0,'returnInfo'=>'发送成功');
        $smsConf = array(
            'key'   => $this->key, //您申请的APPKEY
            'mobile'    => $mobile, //接受短信的用户手机号码
            'tpl_id'    => $tpl_id, //您申请的短信模板ID，根据实际情况修改
            'tpl_value' => $tpl_value//您设置的模板变量，根据实际情况修改['#code#=1234&#company#=聚合数据' ]
        );
        $content = $this->juhecurl($this->sendUrl,$smsConf,1); //请求发送短信
        if($content){
            $result = json_decode($content,true);
            $error_code = $result['error_code'];
            if($error_code == 0){
                //状态为0，说明短信发送成功，插入数据库
                $data['sms_mob'] = $mobile;
                $data['sms_tpl_id'] = $tpl_id;
                $data['sms_tpl_value'] = $tpl_value;
                $data['sms_sid'] = $result['result']['sid'];
                $db = M("sms")->add($data);
                return $msg;
            }else{
                //状态非0，说明失败
                $msg = array('returnCode' => $error_code,'returnInfo' => $result['reason']);
            }
        }else{
             $msg = array('returnCode' => -1,'returnInfo' =>'短信系统异常,请联系服务商');
        }
        return $msg;
    }
	


    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]picc
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    private function juhecurl($url,$params=false,$ispost=0){
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
        curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );
        curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
        curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
        if( $ispost )
        {
            curl_setopt( $ch , CURLOPT_POST , true );
            curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
            curl_setopt( $ch , CURLOPT_URL , $url );
        }
        else
        {
            if($params){
                curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
            }else{
                curl_setopt( $ch , CURLOPT_URL , $url);
            }
        }
        $response = curl_exec( $ch );
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
        $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
        curl_close( $ch );
        return $response;
    }
}
